#region Summary

// 
// Owner : JackieHan 
// 
// Solution : DailyCollection 
// 
// Project : Jackie.Utility.Notify.Services
// 
// File : ImmediatelySender.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 即时发送
// 
// History : 
//			2011-05-05 11:39:44	    Create 
// 

#endregion

#region Using

using System;
using Common.Logging;
using Jackie.Utility.Notify.Domain;
using System.Linq;
using Jackie.Utility.CustomExtension;

#endregion

namespace Jackie.Utility.Notify.Services.Manager.Sender
{
    /// <summary> 
    /// 即时发送
    /// </summary>
    /// <remarks>
    /// 有消息马上发送出去
    /// </remarks>
    public class ImmediatelySender : IMessageSender
    {
        private readonly ILog logger;

        public ImmediatelySender()
        {
            logger = LogManager.GetLogger(GetType());
        }

        public void Send(MessageInfo info)
        {
            var clientManager = ClientManager.GetInstance();
            var clients = clientManager.GetSubscribedClients(info.TitleCode);
            clients.ForEach(item => Send(info, item));
        }


        public void Send(MessageInfo info, ClientSubscribeInfo client)
        {
            logger.Info(string.Format("start to send to client[{0}]", client.ClientSign));
            var isSendSuccess = true;
            try
            {
                client.CallbackInstance.Received(info);
            }
            catch (Exception ex)
            {
                isSendSuccess = false;
                logger.Error("send error!", ex);
            }
            if (isSendSuccess)
                SaveSendHistory(info, client);
            logger.Info(string.Format("end to send"));
        }

        /// <summary>
        /// 如果不是保持连接消息，则记录历史信息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="client"></param>
        private void SaveSendHistory(MessageInfo message, ClientSubscribeInfo client)
        {
            if (message.TitleCode == "KeepAlive") return;
            var sendInfo = new MessageSendInfo()
                               {
                                   Message = message,
                                   SendedClient = client,
                                   SendedTime = DateTime.Now
                               };
            var messageManager = MessageManager.GetInstance();
            messageManager.AddMessageSendedHistory(message, sendInfo);
        }
    }
}